﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp3
{
    public class CheckExtend
    {

        public static List<string> videoUrls = new List<string>
            {
                "http://58.51.111.46:1111/tsfile/live/0001_1.m3u8?key=txiptv&playlive=1&authid=0",
                "http://123.146.162.24:8013/tslslive/noEX9SG/hls/live_sd.m3u8",
                "http://ottrrs.hl.chinamobile.com/TVOD/88888888/224/3221226559/index.m3u8",
                "http://103.116.245.163/sxg/sxg.php?id=/CCTV-1H265_4000.m3u8",
                "http://[2409:8087:1a01:df::4077]/ottrrs.hl.chinamobile.com/yinhe/88888888/224/3221226016/index.m3u8",
                "http://qnap.yjnhome.com:4000/rtp/239.3.1.129:8008",
                "http://183.6.110.242:9901/hls/1001/index.m3u8",
                "http://39.164.202.90:8899/tsfile/live/0001_1.m3u8?key=txiptv&playlive=1&authid=0",
                "https://epg.pw/stream/429ae5e0377c05e43ec9fa7aae9d77ccafe257fdca1816d8044bfd285f231613.m3u8",
                "http://113.220.234.100:9999/tsfile/live/0017_1.m3u8?key=txiptv&playlive=1&authid=0",
                "http://61.136.67.238:50085/tsfile/live/0001_1.m3u8?key=txiptv&playlive=1&authid=0",
                "http://stream.smntv.cn/smtv1/sd/live.m3u8",
                "http://36.32.174.67:60080/newlive/live/hls/1/live.m3u8",
                "http://[2409:8087:1a01:df::7005]:80/ottrrs.hl.chinamobile.com/PLTV/88888888/224/3221226476/index.m3u8",
                "http://171.8.245.118:808/hls/1/index.m3u8",
                "https://epg.pw/stream/0708164a2201ab82eb0c3f2d3ede428571b1b4bb1b8d3cfb3a9ed1201dd2fe68.m3u8",
                "http://124.205.11.246:91/live/CCTV1hd-8M/live.m3u8",
                "http://175.8.213.198:8081/tsfile/live/0001_1.m3u8?key=txiptv&playlive=1&authid=0",
                "http://117.27.190.42:9998/tsfile/live/23232_1.m3u8?key=txiptv&playlive=1&authid=0",
                "http://118.81.54.64:9999/tsfile/live/0001_1.m3u8?key=txiptv&playlive=1&authid=0",
                "http://171.8.171.28:8800/rtp/239.16.20.1:10010",
                "http://183.11.239.36:808/hls/19/index.m3u8",
                "http://[2409:8087:1a01:df::7005]/ottrrs.hl.chinamobile.com/yinhe/88888888/224/3221226559/index.m3u8",
            };


        private async void Check()
        {



            List<Task<(string url, bool isValid, double speed)>> tasks = new List<Task<(string, bool, double)>>();

            foreach (var url in videoUrls)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var (isValid, mediaType, speed) = await CheckVideoUrlAsync(url);
                    return (url, isValid, speed);
                }));
            }

            var results = await Task.WhenAll(tasks);

            var validVideos = results.Where(result => result.isValid)
                                     .Select(result => (result.url, result.speed))
                                     .OrderByDescending(result => result.speed)
                                     .ToList();

            Console.WriteLine("\nSorted valid video URLs by speed:");
            foreach (var video in validVideos)
            {
                Console.WriteLine($"URL: {video.url}, Speed: {video.speed} bytes/second");
            }


        }



        private static readonly HttpClient client = new HttpClient();
        private static readonly SemaphoreSlim semaphore = new SemaphoreSlim(5); // 限制并发数量为5
        public static async Task<(bool, string, double)> CheckVideoUrlAsync(string url)
        {
            try
            {
                await semaphore.WaitAsync();
                HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
                if (response.IsSuccessStatusCode)
                {
                    MediaTypeHeaderValue contentType = response.Content.Headers.ContentType;
                    if (contentType != null && (contentType.MediaType.StartsWith("video") ||
                                                contentType.MediaType == "application/vnd.apple.mpegurl" ||
                                                contentType.MediaType == "application/x-mpegURL"))
                    {
                        Stopwatch stopwatch = new Stopwatch();
                        stopwatch.Start();

                        using (Stream responseStream = await response.Content.ReadAsStreamAsync())
                        {
                            byte[] buffer = new byte[8192];
                            int bytesRead;
                            long totalBytesRead = 0;

                            while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                            {
                                totalBytesRead += bytesRead;
                            }

                            stopwatch.Stop();
                            double downloadTimeInSeconds = stopwatch.Elapsed.TotalSeconds;
                            double speed = totalBytesRead / downloadTimeInSeconds; // 速度：字节/秒

                            return (true, contentType.MediaType, speed);
                        }
                    }
                }
            }
            catch
            {
                // Handle exceptions as needed
            }
            finally
            {
                semaphore.Release();
            }
            return (false, null, 0);
        }



    }
}
